<template>
  <div class="sign-up-bg">
    <div class="sign-up-header">
      <h1>{{ t("login.forgotPassword") }}</h1>
    </div>
    <el-card shadow="always" class="box-card sign-up-card">
      <el-row>
        <el-col class="sign-up-step">
          <el-steps :active="activeStep" align-center>
            <el-step :title="t('forgotPassword.authentication')" />
            <el-step :title="t('forgotPassword.resetPassword')" />
            <el-step :title="t('forgotPassword.resetSuccessful')" />
          </el-steps>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="6">
          <el-alert
            class="sign-up-msg"
            v-if="errorMessage != ''"
            :title="errorMessage"
            @close="onErrorMessageClose"
            type="error"
            effect="dark"
          />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="13" :offset="5" v-if="activeStep == 1">
          <!-- 第一步身份验证 -->
          <div class="sign-up-form">
            <el-form
              ref="form1Ref"
              :model="formEdit1"
              :rules="rules1"
              label-width="150px"
            >
              <el-form-item
                :label="t('forgotPassword.registeredEmail')"
                prop="email"
              >
                <el-input
                  v-model="formEdit1.email"
                  maxlength="64"
                  size="large"
                  clearable
                >
                </el-input>
              </el-form-item>

              <el-form-item
                :label="t('forgotPassword.captcha')"
                prop="emailCaptcha"
              >
                <el-input
                  v-model="formEdit1.emailCaptcha"
                  maxlength="4"
                  size="large"
                  clearable
                  class="fix-el-input-group-append"
                >
                  <template #append>
                    <el-button
                      size="large"
                      :loading="loading1"
                      style="
                        width: 160px;
                        margin: 0 0 0 4px;
                        border: 1px solid var(--el-border-color-light);
                      "
                      :disabled="btnSendMailDisabled"
                      @click="handleSendEmail"
                    >
                      {{ btnSendMailTitle }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>

              <el-button
                ref="btnNext1"
                :disabled="btnNext1Disabled"
                type="primary"
                size="large"
                :loading="loading1"
                style="width: 100%"
                @click="handleStep(2)"
                >{{ t("common.nextStep") }}
              </el-button>
            </el-form>
          </div>
        </el-col>
        <el-col :span="13" :offset="5" v-if="activeStep == 2">
          <!-- 第二步重置密码 -->
          <div class="sign-up-form">
            <el-form
              ref="form2Ref"
              :model="formEdit2"
              :rules="rules2"
              label-width="150px"
            >
              <el-form-item
                :label="t('account.newPassword')"
                prop="newPassword"
              >
                <el-input
                  v-model="formEdit2.newPassword"
                  size="large"
                  :type="type1"
                  @focus="type1 = 'password'"
                  show-password
                  minlength="8"
                  maxlength="20"
                  autocomplete="new-password"
                  clearable
                  @onkeypress="capsLockOn()"
                >
                </el-input>
              </el-form-item>

              <el-form-item
                :label="t('account.confirmPassword')"
                prop="confirmPassword"
              >
                <el-input
                  v-model="formEdit2.confirmPassword"
                  size="large"
                  :type="type2"
                  @focus="type2 = 'password'"
                  show-password
                  minlength="8"
                  maxlength="20"
                  autocomplete="new-password"
                  clearable
                >
                </el-input>
              </el-form-item>

              <div>
                <el-button
                  size="large"
                  :loading="loading1"
                  style="width: 155px; float: left"
                  @click="handleStep(1)"
                  >{{ t("common.previousStep") }}
                </el-button>
                <el-button
                  type="primary"
                  size="large"
                  :loading="loading1"
                  style="width: 222px; float: right"
                  @click="handleResetPassword"
                  >{{ t("common.nextStep") }}
                </el-button>
              </div>
            </el-form>
          </div>
        </el-col>
        <el-col :span="13" :offset="5" v-if="activeStep == 3">
          <!-- 为了保障信息安全，请保管好您的账号和密码 秒后自动跳转到首页-->
          <el-result
            icon="success"
            :title="t('forgotPassword.haveResetPassword')"
            :sub-title="successSec + t('forgotPassword.autoRedirectedLogin')"
          >
            <template #extra>
              <el-button type="primary" @click="handleSuccess">{{
                t("common.finishButton")
              }}</el-button>
            </template>
          </el-result>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <div class="sign-up-notice">
            <label>
              <input ref="agreeRef" type="checkbox" />我已阅读并接受
            </label>
            <a href="#">《注册声明》</a>
            <a href="#">《版权声明》</a>
            <a href="#">《隐私政策》</a>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>

  <!-- https://github.com/javaLuo/vue-puzzle-vcode -->
  <Vcode
    :show="isShow"
    :successText="t('common.vcodeSuccessText')"
    :failText="t('common.vcodeFailText')"
    :sliderText="t('common.vcodeSliderText')"
    @success="handleVerifySuccess"
    @close="handleVerifyClose"
  />
</template>
<script setup lang="ts">
import { getCurrentInstance, reactive, ref, onMounted } from "vue";
import Vcode from "vue3-puzzle-vcode";
import Img1 from "../../assets/images/login-logo.jpg";
import utils from "../../utils/utils";
import { useI18n } from "vue-i18n";
import apiAuth from "./api/auth";
const { t } = useI18n({ useScope: "global" });
import { useRouter } from "vue-router";
const router = useRouter();

const { proxy } = getCurrentInstance() as any;
const sessionId = ref("");
const publicKey = ref("");
const showErrorMessage = ref(true);
const errorMessage = ref("");
const activeStep = ref(1);
const form1Ref = ref();
const form2Ref = ref();
const btnNext1 = ref();
const btnNext1Disabled = ref(true);
const isShow = ref(false);
const loading1 = ref(false);
const type1 = ref("");
const type2 = ref("");
const successSec = ref(10);
const SENDING_EMAIL_SEC = 15;
const sendingEmailSec = ref(SENDING_EMAIL_SEC);
const btnSendMailDisabled = ref(false);
const btnSendMailTitle = ref("");
let timerRedirectLogin: any = null;

const formEdit1 = reactive({
  email: "",
  emailCaptcha: "",
});

const rules1 = reactive({
  email: [
    { required: true, message: t("common.required"), trigger: "blur" },
    {
      type: "email",
      message: () => t("account.emailVerificationFailed"),
      trigger: ["blur", "change"],
    },
  ],
  emailCaptcha: [
    { required: true, message: t("common.required"), trigger: "blur" },
  ],
});

const formEdit2 = reactive({
  newPassword: "",
  confirmPassword: "",
  remark: "",
});

const rules2 = ref({
  newPassword: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (formEdit2.newPassword === "") {
          callback(new Error(t("common.required")));
        } else if (!utils.validatePassword(formEdit2.newPassword)) {
          callback(new Error(t("account.passwordWarning")));
        } else {
          callback();
        }
      },
      trigger: "blur",
      required: true,
    },
  ],
  confirmPassword: [
    { required: true, message: t("common.required"), trigger: "blur" },
    {
      required: true,
      validator: (rule, value, callback) => {
        if (formEdit2.newPassword !== value) {
          callback(new Error(t("account.passwordInconsistent")));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const onErrorMessageClose = () => {
  errorMessage.value = "";
  showErrorMessage.value = false;
};

const capsLockOn = () => {};

const getPublicKey = () => {
  sessionId.value = utils.getUUID();
  apiAuth
    .generateSessionPublicKeyQ(sessionId.value)
    .then((response: any) => {
      if (response.data.code == 200) {
        publicKey.value = response.data.data;
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

// 点击获取验证码按钮，显示滑块验证码，后续操作在滑块验证通过事件中处理
const handleSendEmail = async () => {
  // 验证邮件地址有效性
  let validate = false;
  await form1Ref.value.validateField(["email"], (valid: any) => {
    // console.log("handelSendEmail valid", valid);
    validate = valid;
  });
  if (!validate) return;

  errorMessage.value = "";
  sendingEmailSec.value = SENDING_EMAIL_SEC;
  btnNext1Disabled.value = true;
  isShow.value = true;
};

// 点击下一步按钮，显示滑块验证码，后续操作在滑块验证通过事件中处理
const handleResetPassword = async () => {
  await form2Ref.value.validate();
  isShow.value = true;
};

const handleSuccess = () => {
  clearTimeout(timerRedirectLogin);
  router.push({
    name: "login",
    // params: { menuId: row.menuId },
  });
};

// 行为验证码回调
const handleVerifySuccess = (params: any) => {
  // console.log("handleVerifySuccess", params);
  isShow.value = false;
  if (activeStep.value == 1) {
    // 验证邮件地址有效性触发
    // 加密数据
    let jsonString = utils.jsonObject2JsonString({
      email: formEdit1.email,
      random: utils.getUUID(),
    });
    let encryptedPassword = utils.doSm2Encrypt(publicKey.value, jsonString);

    apiAuth
      .sendEmailCaptchaByForgotPassword(sessionId.value, encryptedPassword)
      .then((response: any) => {
        if (response.data.code == 200) {
          btnSendMailDisabled.value = true;
          handleSendingEmailDown();
        } else {
          errorMessage.value = response.data.msg;
        }
      });
  } else if (activeStep.value == 2) {
    // 点击下一步按钮，提交服务器重置的新密码，进入完成界面
    handleStep(3);
  }
};

const handleVerifyClose = () => {
  isShow.value = false;
};

// 发送邮件倒计时
const handleSendingEmailDown = () => {
  if (sendingEmailSec.value > 0) {
    setTimeout(() => {
      sendingEmailSec.value = sendingEmailSec.value - 1;
      btnSendMailTitle.value = t("forgotPassword.sendingMail", {
        sec: sendingEmailSec.value,
      });
      handleSendingEmailDown();
    }, 1000);
  } else {
    btnSendMailTitle.value = t("forgotPassword.hasBeenSent");
    btnNext1Disabled.value = false;
  }
};

const handleStep = async (step: number) => {
  // console.log(activeStep.value, step);
  if (activeStep.value == 1 && step == 2) {
    // 第一个下一步，验证邮件验证码是否正确
    await form1Ref.value.validate();
    errorMessage.value = "";
    // 验证邮箱和验证码
    // 加密数据
    let jsonString = utils.jsonObject2JsonString({
      captcha: formEdit1.emailCaptcha,
      random: utils.getUUID(),
    });
    let encryptedCaptcha = utils.doSm2Encrypt(publicKey.value, jsonString);

    apiAuth
      .validateEmailByForgotPassword(sessionId.value, encryptedCaptcha)
      .then((response: any) => {
        // console.log("handleVerifySuccess", res)
        if (response.data.code == 200) {
          activeStep.value = step;
          btnNext1Disabled.value = false;
        } else {
          errorMessage.value = response.data.msg;
          sendingEmailSec.value = SENDING_EMAIL_SEC;
          btnSendMailTitle.value = t("forgotPassword.getCaptcha");
          btnNext1Disabled.value = true;
          btnSendMailDisabled.value = false;
        }
      });
  } else if (activeStep.value == 2 && step == 1) {
    // 上一步，回到第一步
    formEdit1.emailCaptcha = "";
    errorMessage.value = "";
    sendingEmailSec.value = SENDING_EMAIL_SEC;
    btnSendMailTitle.value = t("forgotPassword.getCaptcha");
    btnNext1Disabled.value = true;
    btnSendMailDisabled.value = false;
    activeStep.value = step;
  } else if (activeStep.value == 2 && step == 3) {
    //第二个 下一步
    await form2Ref.value.validate();
    errorMessage.value = "";

    // 加密数据
    let jsonString = utils.jsonObject2JsonString({
      password: formEdit2.newPassword,
      random: utils.getUUID(),
    });
    let encryptedCaptcha = utils.doSm2Encrypt(publicKey.value, jsonString);

    // 找回密码
    apiAuth.resetPassword(sessionId.value, encryptedCaptcha).then((res) => {
      // console.log("sign-up", res)
      if (res.data.code == 200) {
        activeStep.value = step;
        handleSuccessDown();
      } else {
        errorMessage.value = res.data.msg;
      }
    });
  }
};

const handleSuccessDown = () => {
  if (successSec.value > 0) {
    timerRedirectLogin = setTimeout(() => {
      successSec.value = successSec.value - 1;
      handleSuccessDown();
    }, 1000);
  } else {
    router.push({
      name: "login",
      // params: { menuId: row.menuId },
    });
  }
};

onMounted(() => {
  getPublicKey();
  btnSendMailTitle.value = t("forgotPassword.getCaptcha");
});
</script>
<style lang="scss" scoped>
.sign-up-bg {
  height: 100%;
  width: 100%;
  display: block;
  overflow: hidden !important;
  /* fix 禁止出现滚动条 */
  position: fixed;
}

.sign-up-bg::before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  /* fix 白边，去掉白边出现滚动条 */
  margin: -50px;
  //   background-image: url("https://img-qn.51miz.com/2017/03/26/21/2017032621720647_P213012_a40f5760.jpeg!/quality/90/unsharp/true/compress/true/fwfh/830x400");
  //   background-image: url("https://img-qn.51miz.com/2017/03/26/21/2017032621709684_P213266_cda09ee4.jpeg!/quality/90/unsharp/true/compress/true/fw/900");
  //   background-image: url("https://img-qn.51miz.com/preview/photo/00/01/51/46/P-1514665-BFD743FF.jpg!/quality/90/unsharp/true/compress/true/fwfh/830x400");
  //   background-image: url("https://img-qn.51miz.com/preview/photo/00/01/54/87/P-1548767-B4DD056A.jpg!/quality/90/unsharp/true/compress/true/fwfh/830x400");
  //   background-image: url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpmtc65a49.pic20.websiteonline.cn%2Fupload%2F7fc531f98ce76d3274b8db3fcd75fcde_uwsz.jpeg&refer=http%3A%2F%2Fpmtc65a49.pic20.websiteonline.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649574693&t=1d96a4193037c430b35e5658042d46d5");
  //   background-image: url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.xinhuanet.com%2Fbook%2F2020-07%2F20%2F139225694_15952117732871n.jpg&refer=http%3A%2F%2Fwww.xinhuanet.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649577156&t=b84399f704c431c16ecb62da33bae8f3");
  //   background-image: url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091122%2Fwh4ixl0qwwywh4ixl0qwwy.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649578369&t=39050d2ac16fb237bc64b91a6df94e36");
  // background-image: url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-a3b927b4ec290517619301ef72d86f4e_1440w.jpg%3Fsource%3D172ae18b&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649574778&t=c9035ed9f8d5ecf54b7465a9f952bc41");
  //   background-image: url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2018-11-20%2F5bf3f1badc437.jpg%3Fdown&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649578785&t=7f43a7837bc954995840c6c9f7251e3d");
  background-color: #f0f2f5;
  background-position: center center;
  background-size: cover;
}

.sign-up-header {
  position: absolute;
  top: 0;
  height: 60px;
  width: 100%;
  display: block;
  background-color: #fff;

  h1 {
    font-weight: normal;
    font-size: 24px;
    line-height: 100%;
    padding-left: 100px;
    color: #666;
  }
}

::v-deep(.sign-up-card) {
  width: 780px;
  left: calc(50% - 780px / 2);
  top: calc(100% / 2 - 250px);
  position: absolute;
  z-index: 100;
  border-radius: 0;

  .el-card__body {
    padding: 0 !important;
  }

  .el-alert,
  .el-input,
  .el-button,
  .el-radio-button__inner,
  .el-radio-button {
    --el-input-border-radius: 0 !important;
    border-radius: 0;
  }
}

.sign-up-step {
  padding: 40px 0 40px 0;
}

.sign-up-msg {
  margin: 0 auto;
}

.sign-up-form {
  padding: 30px 0;
}

.sign-up-form h1 {
  text-align: center;
  font-weight: normal;
  margin-bottom: 50px;
  // color: var(--el-color-primary-light-1);
  color: #4b9ff8;
}

.sign-up-notice {
  display: block;
  background-color: #fafafa;
  color: var(--el-color-info);
  font-size: 12px;
  text-align: center;
  margin-top: 30px;
  padding: 15px;
  position: relative;
  bottom: 0;

  input {
    vertical-align: top;
  }

  a {
    text-decoration: none;
    color: var(--el-color-info);
  }
}
</style>
<style>
/* 图形验证码 */
.fix-el-input-group-append .el-input-group__append,
.fix-el-input-group-append .el-input-group__prepend {
  padding: 0;
  background-color: #fff;
  border: 0;
  box-shadow: none;
  border-radius: 0;
}
</style>
